package util.parser;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.Map;

import util.webSearch.GoogleQuery;

public class ParseGoogleSuggestions {

	/**
	 * @param args
	 */

	public static LinkedList<String> suggestions(String query, String post) {

		post = post.toLowerCase();
		LinkedList<String> list = new LinkedList<String>();
		LinkedList<Long> list_freq = new LinkedList<Long>();
		Hashtable<String, Long> hash = new Hashtable<String, Long>();

		String[] suggestions = post.split("suggestion data=\"");
		String[] freq = post.split("num_queries int=\"");

		for (int i = 0; i < suggestions.length; i++) {

			if (suggestions[i].contains("xml version=")) {

				continue;
			}

			int index = suggestions[i].indexOf("\"");
			String sugge = suggestions[i].substring(0, index);

			list.add(sugge);
			

		}

		for (int i = 0; i < freq.length; i++) {

			if (freq[i].contains("xml version=")) {

				continue;
			}

			int index = freq[i].indexOf("\"");
			Long sugge = Long.valueOf(freq[i].substring(0, index));

			list_freq.add(sugge);
		
		}

		for (int i = 0; i < list_freq.size(); i++) {
			hash.put(list.get(i), list_freq.get(i));
		}

		// sort list by frequency and generate sorted list of suggestions

		list = sortHash(hash, query);

		return list;
	}

	public static LinkedList<String> sortHash(Hashtable<String, Long> hash,
			String query) {

		ArrayList myArrayList = new ArrayList(hash.entrySet());
		LinkedList<String> list = new LinkedList<String>();
		// Sort the values based on values first and then keys.
		Collections.sort(myArrayList, new MyComparator());

		// Show sorted results
		Iterator itr = myArrayList.iterator();
		String key = "";

		while (itr.hasNext()) {

			Map.Entry e = (Map.Entry) itr.next();

			key = (String) e.getKey();
			if (key.equals(query))
				continue;

			list.add(key);

		}

		return list;
	}

	public static void main(String[] args) {
		// TODO Auto-generated method stub

	}

	static class MyComparator implements Comparator {

		public int compare(Object obj1, Object obj2) {

			int result = 0;
			Map.Entry e1 = (Map.Entry) obj1;

			Map.Entry e2 = (Map.Entry) obj2;// Sort based on values.

			Long value1 = (Long) e1.getValue();
			Long value2 = (Long) e2.getValue();

			if (value1.compareTo(value2) == 0) {

				String word1 = (String) e1.getKey();
				String word2 = (String) e2.getKey();

				// Sort String in an alphabetical order
				result = word1.compareToIgnoreCase(word2);

			} else {
				// Sort values in a descending order
				result = value2.compareTo(value1);
			}

			return result;
		}

	}

}
